using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using System.Text;

namespace BlazeApps.Library.Menus
{
    [Serializable()]
    public class MenuTreeNodeDetail : Csla.BusinessBase<MenuTreeNodeDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private int _id = 0;
        private string _title = string.Empty;
        private string _description = string.Empty;
        private string _url = string.Empty;
        private string _roles = string.Empty;
        private int _parent = 0;
        private int _parentchildcount = 0;

        [System.ComponentModel.DataObjectField(true, true)]
        public int Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
            set
            {
                CanWriteProperty("Id", true);
                if (!_id.Equals(value))
                {
                    _id = value;
                    PropertyHasChanged("Id");
                }
            }
        }

        public string Title
        {
            get
            {
                CanReadProperty("Title", true);
                return _title;
            }
            set
            {
                CanWriteProperty("Title", true);
                if (value == null)
                    value = string.Empty;
                if (!_title.Equals(value))
                {
                    _title = value;
                    PropertyHasChanged("Title");
                }
            }
        }

        public string Description
        {
            get
            {
                CanReadProperty("Description", true);
                return _description;
            }
            set
            {
                CanWriteProperty("Description", true);
                if (value == null)
                    value = string.Empty;
                if (!_description.Equals(value))
                {
                    _description = value;
                    PropertyHasChanged("Description");
                }
            }
        }

        public string Url
        {
            get
            {
                CanReadProperty("Url", true);
                return _url;
            }
            set
            {
                CanWriteProperty("Url", true);
                if (value == null)
                    value = string.Empty;
                if (!_url.Equals(value))
                {
                    _url = value;
                    PropertyHasChanged("Url");
                }
            }
        }

        public string Roles
        {
            get
            {
                CanReadProperty("Roles", true);
                return _roles;
            }
            set
            {
                CanWriteProperty("Roles", true);
                if (value == null)
                    value = string.Empty;
                if (!_roles.Equals(value))
                {
                    _roles = value;
                    PropertyHasChanged("Roles");
                }
            }
        }

        public int Parent
        {
            get
            {
                CanReadProperty("Parent", true);
                return _parent;
            }
            set
            {
                CanWriteProperty("Parent", true);
                if (!_parent.Equals(value))
                {
                    _parent = value;
                    PropertyHasChanged("Parent");
                }
            }
        }

        public int ParentChildCount
        {
            get
            {
                CanReadProperty("ParentChildCount", true);
                return _parentchildcount;
            }
            set
            {
                CanWriteProperty("ParentChildCount", true);
                if (!_parentchildcount.Equals(value))
                {
                    _parent = value;
                    PropertyHasChanged("ParentChildCount");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {

        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in MenuTreeNodeDetail
            //AuthorizationRules.AllowRead("Id", "MenuTreeNodeDetailReadGroup");
            //AuthorizationRules.AllowRead("Title", "MenuTreeNodeDetailReadGroup");
            //AuthorizationRules.AllowRead("Description", "MenuTreeNodeDetailReadGroup");
            //AuthorizationRules.AllowRead("Url", "MenuTreeNodeDetailReadGroup");
            //AuthorizationRules.AllowRead("Roles", "MenuTreeNodeDetailReadGroup");
            //AuthorizationRules.AllowRead("Parent", "MenuTreeNodeDetailReadGroup");

            //AuthorizationRules.AllowWrite("Title", "MenuTreeNodeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Description", "MenuTreeNodeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Url", "MenuTreeNodeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Roles", "MenuTreeNodeDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Parent", "MenuTreeNodeDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in MenuTreeNodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("MenuTreeNodeDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in MenuTreeNodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("MenuTreeNodeDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in MenuTreeNodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("MenuTreeNodeDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in MenuTreeNodeDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("MenuTreeNodeDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private MenuTreeNodeDetail()
        { /* require use of factory method */
        }

        public static MenuTreeNodeDetail NewMenuTreeNodeDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a MenuTreeNodeDetail");
            return DataPortal.Create<MenuTreeNodeDetail>();
        }

        public static MenuTreeNodeDetail GetMenuTreeNodeDetail(int id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a MenuTreeNodeDetail");
            return DataPortal.Fetch<MenuTreeNodeDetail>(new Criteria(id));
        }

        public static void DeleteMenuTreeNodeDetail(int id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a MenuTreeNodeDetail");
            DataPortal.Delete(new Criteria(id));
        }

        public override MenuTreeNodeDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a MenuTreeNodeDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a MenuTreeNodeDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a MenuTreeNodeDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public int Id;

            public Criteria(int id)
            {
                this.Id = id;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@id", criteria.Id);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetMenuByMenuID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _id = dr.GetInt32("ID");
            _title = dr.GetString("Title");
            _description = dr.GetString("Description");
            _url = dr.GetString("Url");
            _roles = dr.GetString("Roles");
            _parent = dr.GetInt32("Parent");
            _parentchildcount = dr.GetInt32("parentchildcount");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertMenu.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {

            if (_title.Length > 0)
                DAL.AddParameter("@Title", _title);
            else
                DAL.AddParameter("@Title", DBNull.Value);
            if (_description.Length > 0)
                DAL.AddParameter("@Description", _description);
            else
                DAL.AddParameter("@Description", DBNull.Value);
            if (_url.Length > 0)
                DAL.AddParameter("@Url", _url);
            else
                DAL.AddParameter("@Url", DBNull.Value);
            if (_roles.Length > 0)
                DAL.AddParameter("@Roles", _roles);
            else
                DAL.AddParameter("@Roles", DBNull.Value);
            if (_parent != 0)
                DAL.AddParameter("@Parent", _parent);
            else
                DAL.AddParameter("@Parent", DBNull.Value);           
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateMenu.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@ID", _id);
            if (_title.Length > 0)
                DAL.AddParameter("@Title", _title);
            else
                DAL.AddParameter("@Title", DBNull.Value);
            if (_description.Length > 0)
                DAL.AddParameter("@Description", _description);
            else
                DAL.AddParameter("@Description", DBNull.Value);
            if (_url.Length > 0)
                DAL.AddParameter("@Url", _url);
            else
                DAL.AddParameter("@Url", DBNull.Value);
            if (_roles.Length > 0)
                DAL.AddParameter("@Roles", _roles);
            else
                DAL.AddParameter("@Roles", DBNull.Value);
            if (_parent != 0)
                DAL.AddParameter("@Parent", _parent);
            else
                DAL.AddParameter("@Parent", DBNull.Value);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteMenu.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@id", criteria.Id);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
